﻿<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.debug.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.debug.js"></script>

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->
</asp:Content>


<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

   <script type="text/javascript">
       var theWindow = null;
       function setIFrameUrl() {
           //theWindow = window.open(document.getElementById('theUrl').value, "window", 'width=800,height=600', false);
           theWindow = document.getElementById("previewFrame").contentWindow;
           theWindow.location = document.getElementById('theUrl').value;
       }

       function getCtxFromIFrame() {
           function addOverrideCbx(parentField, name, isField) {
               var opt = document.createElement('li');
               var optStr = "";
               optStr += '<span><label' + (isField ? ' class="fieldName"' : '') + '>' + name + '</label>&nbsp;';
               optStr += '<label for="' + name + '_tmpl">Template</label><input type="checkbox" name="' + name + '_tmpl" title="Template" />&nbsp;';
               optStr += '<label for="' + name + '_onPostRender">OnPostRender</label><input type="checkbox" name="' + name + '_onPostRender" title="OnPostRender" />';
               optStr += '</span>';
               opt.innerHTML = optStr;
               opt.id = "field_" + idx;

               parentField.appendChild(opt);
           }

           var selFields = document.getElementById('fieldsList');
           selFields.innerHTML = ""; // empty the existing items

           addOverrideCbx(selFields, "View", false);
           addOverrideCbx(selFields, "Group", false);
           addOverrideCbx(selFields, "Item", false);

           var idx = 0;
           for (idx = 0; idx < theWindow.ctx.ListSchema.Field.length; ++idx) {
               addOverrideCbx(selFields, theWindow.ctx.ListSchema.Field[idx].Name, true);
           }

           var dataTable = document.getElementById('dataTable');
           for (idx = 0; idx < theWindow.ctx.ListData.Row.length; ++idx) {
               var row = theWindow.ctx.ListData.Row[idx];
               var elemTR = document.createElement('tr');
               var strTdHtml = [];
               for (var fieldName in row) {
                   strTdHtml.push('<td>"' + fieldName + '":' + row[fieldName] + '</td>');
               }
               elemTR.innerHTML = strTdHtml.join('');
               dataTable.appendChild(elemTR);
           }
       }

       function generateScript() {
           var scriptPrefix = "debugger; \n\
\n\
function Overrides() {\n\
    var overrideCtx = {};\n\
\n\
    overrideCtx.BaseViewID = '{BASEVIEWID}';\n\
    overrideCtx.ListTemplateType = {LISTTEMPLATETYPE};\n\
\n\
    overrideCtx.Templates = {};\n\
\n";
           var scriptFields = "\
    overrideCtx.Templates.Fields = {\n";
           var scriptFieldOverride = "\
                                                        '{FieldName}': { 'View': {FieldName}_ViewFieldOverride },\n";
           var scriptTestField = "        'LinkTitle': { 'View': 'foo' },\n";

           var scriptOnPreRender = "    };\n\
\n\
    overrideCtx.OnPreRender  = [\n";
           var scriptOnPostRender = "    ];\n\
    overrideCtx.OnPostRender = [\n";
           var scriptFieldOverrideOnPostrender = "\
                                {FieldName}_FieldOnPostRender,\n";
           var scriptSuffix = "    ];\n\
\n\
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);\n\
};\n\
\n";

           var scriptMDS = "RegisterModuleInit('MyFile.js', Overrides);    // Register CSR-override method for MDS mode\n\
Overrides();                                   // Register CSR-override method for non-MDS mode\n\
\n\
/*********************************************************\n\
* Methods needed for ScriptOnDemand, DO NOT REMOVE !\n\
**********************************************************/\n\
if (typeof (Sys) != 'undefined' && Boolean(Sys) && Boolean(Sys.Application)) {\n\
    Sys.Application.notifyScriptLoaded();\n\
}\n\
if (typeof (NotifyScriptLoadedAndExecuteWaitingJobs) == 'function') {\n\
    NotifyScriptLoadedAndExecuteWaitingJobs('MyFile.js');\n\
}";

           var scriptFieldOverrideTempl = "function {FieldName}_ViewFieldOverride(inCtx, field, listItem, listSchema) {\n\
    var fieldValue = listItem[field.RealFieldName];\n\
    var iid = GenerateIIDForListItem(inCtx, listItem);\n\
    var ret = [];\n\
\n\
    // do stuff here\n\
    ret.push('<b>' + fieldValue + '</b>');\n\
\n\
\n\
    return ret.join('');\n\
}\n\
\n";

           var scriptVal = "";
           var scriptFuncs = "";
           scriptVal += scriptPrefix.replace('{BASEVIEWID}', theWindow.ctx.BaseViewID).replace('{LISTTEMPLATETYPE}', theWindow.ctx.ListTemplateType);
           scriptVal += scriptFields;

           var fieldNodes = document.querySelectorAll(".fieldName");
           for (var idx = 0; idx < fieldNodes.length; ++idx) {
               var fldName = fieldNodes[idx].innerText;
               //if (useTemplate) {
               scriptVal += scriptFieldOverride.replace('{FieldName}', fldName).replace('{FieldName}', fldName);
               scriptFuncs += scriptFieldOverrideTempl.replace('{FieldName}', fldName);
               //}
               //else if (usePostRender) {
               //    scriptVal += scriptFieldOverride.replace('{FieldName}', 'LinkTitle').replace('{FieldName}', fldName);
               //    scriptFuncs += scriptFieldOverrideTempl.replace('{FieldName}', fldName);
               //}
           }

           scriptVal += scriptOnPreRender;
           scriptVal += scriptOnPostRender;
           scriptVal += scriptSuffix;
           scriptVal += scriptFuncs;
           scriptVal += scriptMDS;

           document.getElementById('scriptBox').value = scriptVal;
       }

       function insertScriptIntoIFrame() {
           // clean field renderers
           for (var i = 0; i < theWindow.ctx.ListSchema.Field.length; ++i) {
               if (typeof theWindow.ctx.ListSchema.Field[i].fieldRenderer != 'undefined') {
                   theWindow.ctx.ListSchema.Field[i].fieldRenderer = null;
                   delete theWindow.ctx.ListSchema.Field[i].fieldRenderer;
               }

               if (typeof theWindow.ctx.ListSchema.Field[i].FieldRenderer != 'undefined') {
                   theWindow.ctx.ListSchema.Field[i].FieldRenderer = null;
                   delete theWindow.ctx.ListSchema.Field[i].FieldRenderer;
               }
           }
           theWindow.ctx.Templates = null;

           // delete the script and scriptPaging contents
           theWindow.document.getElementById('script' + theWindow.ctx.wpq).innerHTML = "";
           var scriptPagingNode = theWindow.document.getElementById('scriptPaging' + theWindow.ctx.wpq).innerHTML = "";

           var scriptElem = theWindow.document.getElementById('csrFiddler');
           if (scriptElem != null)
               theWindow.document.body.removeChild(scriptElem);

           scriptElem = theWindow.document.createElement('script');
           scriptElem.innerHTML = document.getElementById('scriptBox').value + "ctx.bInitialRender = true;RenderListView(ctx, ctx.wpq);ctx.bInitialRender = false;";

           theWindow.document.body.appendChild(scriptElem);
       }

    </script>

    <div id="step1">
        <span>Note: Due to same origin security measures, the list being inspected MUST be on the same domain as where this page is hosted.</span><br />
        <span>Step 1: Open the list view</span><br />
        <input type="time" id="theUrl" value="../Lists/SampleList" /><input type="button" name="btnInsertScript" title="Go" value="Go" onclick="javascript: setIFrameUrl(); document.getElementById('step2').removeAttribute('style');" />
    </div>

    <div id="step2" style="display: none">
        <span>Step 2: Grab the context info from the view</span><br />
        <input type="button" id="btnGetCtx" name="GetCtx" title="Get Ctx" value="Get Ctx" onclick="javascript: getCtxFromIFrame(); document.getElementById('step3').removeAttribute('style');" /><br />
        
        <ul id="fieldsList"></ul><br />
    </div>

    <div id="step3" style="display: none">
        <span>Step 3: Generate the template override script</span><br />
        <input type="button" id="btnGenerateScript" name="Generate Script" title="Generate Script" value="Generate Script" onclick="javascript: generateScript(); document.getElementById('step4').removeAttribute('style'); document.getElementById('step5').removeAttribute('style');" /><br />
    </div>
    <div id="step4" style="display: none">
        <span>Step 4: Edit the generated script</span><br />
        <textarea id="scriptBox" style="width: 600px; height: 400px;"></textarea>
    </div>
    <div id="step5" style="display: none">
        <span>Step 5: Try it out!</span><br />
        <input type="button" id="btnInsertScript" title="Insert Script" value="Insert Script" onclick="javascript: insertScriptIntoIFrame();" /><br />
    </div>

    <div style="display:none">
        <span>ListData</span><br />
        <table id="dataTable"></table>
    </div>


</asp:Content>
